<?php
namespace App\Think\SdkGame;

class IMTY{

    // 商家名称/商家密钥
    // baoteprod
    // OrftsPzDRBsxkwTwwYL9CAcpxNivVXbT

    // API域名/前缀
    // http://imone.imaegisapi.com
    // IM2XN

    // 后台管理域名/管理账号/密码
    // http://qbm8y.aegis88.com
    // admin
    // asdf1234

    // IM 体育后台管理域名http://qbm8y-sfbo.imsbbo.com/
    // 管理账号  admin
    // 密码  asdf1234

    // IM电竞后台管理域名/管理账号/密码
    // https://qbm8y-esbo.inplaymatrix.com/
    // QBM8Y
    // asdf1234

    // IM体育黑名单IP搜素后台/账号/密码
    // https://purpledaan.inplaymatrix.com
    // inplaymatrix
    // LekFMZ3Q

    public function __construct()
    {
        // api地址
        $this->api_url  = 'http://imone.imaegisapi.com/';
        // $this->pull_url = 'https://record.pe2020888.me/';

        $this->MerchantCode = 'OrftsPzDRBsxkwTwwYL9CAcpxNivVXbT';
        $this->plat_type  = 'IMTY';
        // $this->platformCode = 'AG';
        $this->ProductWallet = 301;

        $this->password_init = 'baote123A';
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
          "MerchantCode" => $this->MerchantCode,
          "PlayerId"     => $param['account'],
          "Currency"     => "CNY",
          "Password"     => $this->password_init,
          "Country"      => "CN",
          "Sex"          => "M",
          "BirthDate"    => "19900101"

          // "MerchantCode" => "OrftsPzDRBsxkwTwwYL9CAcpxNivVXbT",
          // "PlayerId"     => "myPlayerId",
          // "Currency"     => "CNY",
          // "Password"     => "mypassword",
          // "Country"      => "CN",
          // "Sex"          => "M",
          // "BirthDate"    => "19701128"

        );
        $url = $this->build_url('api','Player/Register');
        $res = $this->sendRequest($url, $req_data);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        $req_data = array(
            "MerchantCode"=> $this->MerchantCode,
            "PlayerId"=> $param['account'],
            "GameCode"=> "IMSB",
            "Language"=> "ZH-CN",
            "IpAddress"=> request()->ip(),
            "ProductWallet"=> $this->ProductWallet,
            "Http"=> 1,
            "IsDownload"=> 0,
            "LobbyURL"=> "http://operatorurl.com/lobby",
            // "Tray"=> "A",
            "Route"=> 1,
            "BetLimitId"=> 1,
            //"RoomId"=> "10001",
            "ShowTrial"=> 0
        );

        $device_url = @$param['device'] == 'pc' ? 'Game/NewLaunchGame' : 'Game/NewLaunchMobileGame';
        $url = $this->build_url('api', $device_url);
        $res = $this->sendRequest($url, $req_data);
        // print_r($res);
        return ['code'=>$res['code'], 'url'=>$res['data']['GameUrl'] ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            'MerchantCode' => $this->MerchantCode,
            'PlayerId'     => $param['account'],
            'ProductWallet'=> $this->ProductWallet,
        );
        $url = $this->build_url('api', 'Player/GetBalance');
        $res = $this->sendRequest($url, $req_data);
        return ['code'=>$res['code'], 'balance'=>(float)$res['data']['Balance'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'MerchantCode' => $this->MerchantCode,
            'PlayerId'     => $param['account'],
            // 'userPassWord' => $this->password_init,
            'TransactionId'=> $param['orderid'],
            'ProductWallet'=> $this->ProductWallet,
            'Amount'       => $param['money'],
        );
        $url = $this->build_url('api', 'Transaction/PerformTransfer');
        $res = $this->sendRequest($url, $req_data);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'MerchantCode' => $this->MerchantCode,
            'PlayerId'     => $param['account'],
            // 'userPassWord' => $this->password_init,
            'TransactionId'=> $param['orderid'],
            'ProductWallet'=> $this->ProductWallet,
            'Amount'       => -$param['money'],
        );
        $url = $this->build_url('api', 'Transaction/PerformTransfer');
        $res = $this->sendRequest($url, $req_data);
        return $res;
    }

    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        $req_data = array(
            'MerchantCode'    => $this->MerchantCode,
            'StartDate'       => date('Y-m-d H.i.s', strtotime($param['startTime'])),
            'EndDate'         => date('Y-m-d H.i.s', strtotime($param['endTime'])),
            'Page'            => 1,
            // 'PageSize'     => 50000,
            // 'BetStatus'       => 1,  //0=未结算，1=已结束
            'ProductWallet'   => $this->ProductWallet,
            'DateFilterType'  => "1",
            'LastUpdatedDate' => date('Y-m-d H.i.s', strtotime($param['startTime'])),
            'Language'        => "ZH-CN"
        );

        $url = $this->build_url('api', 'Report/GetBetLog');
        $res = $this->sendRequest($url, $req_data);
print_r($req_data); 
print_r($res);
exit;
return false;
        //数据返回处理
        $list = @$res['data'];
        // print_r($list);
        $rs = $raw_data = [];
        if(is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                if($v['IsCancelled'] == 1) continue;
                $status = $v['IsSettled'];
                //流水
                if($v['WinLoss'] < 0)  $money_valid = -$v['WinLoss']<$v['StakeAmount'] ? -$v['netPnl'] : $v['StakeAmount'];
                if($v['netPnl'] >= 0) $money_valid = $v['netPnl']<$v['StakeAmount'] ? $v['netPnl'] : $v['StakeAmount'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $v['GameType'],
                    'game_name'     => $v['GameName'],
                    'game_user'     => $v['PlayerId'],
                    'bet_id'        => $v['BetId'],
                    'money_bet'     => $v['StakeAmount'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $v['WinLoss'],
                    'money_fee'     => 0,
                    'createtime'    => strtotime($v['WagerCreationDateTime']),
                    'updatetime'    => strtotime($v['LastUpdatedDate']),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $v['BetId'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($v['LastUpdatedDate']);
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == -101 ? 1 : $res['code'];
        return $res;
    }


    /**
     * 业务 ======== start =========//
     */
    //游戏列表
    public function game_list(){
        $res = file_get_contents(dirname(__FILE__).'/AGZR_data.txt');
        $list = json_decode($res, true);
        return $list;
    }
    //游戏名称
    public function game_name($gameCode){
        $list = $this->game_list();
        foreach ($list as $k => $v) {
          if($v['gameType'] == $gameCode) return $v['gameName'];
        }
        return '未知游戏';
        // return isset($list[$gameType]) ? $list[$gameType] : '未知游戏';
    }


    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url, $post_data=array(), $req_type=1){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //POST
        if($req_type == 1){ 
            curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            $jsonStr = json_encode($post_data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length: ' . strlen($jsonStr)
                )
            );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        $contents = json_decode($contents, true);

        // print_r($jsonStr);
        // print_r($contents);
        //业务处理
        // $res = $contents;
        if(!isset($contents['Code'])){
          $res['code'] = -1;
          return $res;  
        } 
        if($contents['Code'] == 0 || $contents['Code'] == 558){
            $res['code'] = 1;  
        }else{
            $res['code'] = $contents['Code'] > 0 ? -$contents['Code'] : -1;
        }
        $res['msg']  = $contents['Message'];
        $res['data'] = @$contents;
        return $res;
    }

    
    private function build_url($type='api', $act='', $param=[]){
        // $param =  http_build_query($param);
        $api_url = $this->api_url;
        return $api_url.$act;
    }

}

